<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>流程分类管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/css/public.css" media="all"/>
    <link rel="stylesheet" href="/layui_ext/dtree/dtree.css" media="all"/>
    <link rel="stylesheet" href="/layui_ext/dtree/font/dtreefont.css" media="all"/>
</head>
<body class="childrenBody">
<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="categoryTable" lay-filter="categoryTable"></table>
    <div id="categoryToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm" shiro:hasPermission="category:create">
            <span class="layui-icon layui-icon-add-1"></span>添加分类
        </button>
    </div>

    <div id="categoryRowBar" style="display: none;">
        <button type="button" lay-event="edit" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-edit"></span>编辑
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger"
                shiro:hasPermission="category:delete">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
    </div>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->
<div style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form action="" method="post" class="layui-form layui-form-pane" id="dataFrm" lay-filter="dataFrm">
        <input type="hidden" name="id">

        <div class="layui-form-item">
            <label class="layui-form-label">分类名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入分类名称"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">父级分类</label>
            <div class="layui-input-block">
                <input type="hidden" name="parentId" id="parentId" lay-verify="required">
                <ul id="parentTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">节点路径</label>
            <div class="layui-input-block">
                <input type="text" name="path" placeholder="请输入节点路径" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">类型</label>
            <div class="layui-input-block">
                <input type="radio" name="type" value="1" title="分类">
                <input type="radio" name="type" value="0" title="流程类型">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否可用</label>
            <div class="layui-input-block">
                <input type="radio" name="available" checked="" value="1" title="可用">
                <input type="radio" name="available" value="0" title="禁用">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit="" lay-filter="doSubmit">
                    <span class="layui-icon layui-icon-ok"></span>提交
                </button>
                <button type="reset" class="layui-btn layui-btn-warm">
                    <span class="layui-icon layui-icon-refresh-1"></span>重置
                </button>
            </div>
        </div>
    </form>
</div>
<!-- 添加和修改的弹出层结束 -->
<script type="text/javascript" src="/layui/layui.js"></script>
<script type="text/javascript" th:inline="none">
    layui.extend({
        dtree: '/layui_ext/dtree/dtree'
    }).use(['jquery', 'form', 'table', 'layer', 'dtree'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var dtree = layui.dtree;

        // 表格渲染配置（关键修正部分）
        var tableIns = table.render({
            elem: '#categoryTable',
            url: '/category/list',
            toolbar: '#categoryToolBar',
            title: '流程分类列表',
            height: 'full-35',
            page: true,
            cols: [[
                {field: 'id', title: 'ID', align: 'center'},
                {field: 'parentId', title: '父级ID', align: 'center'},
                {field: 'name', title: '分类名称', align: 'center'},
                {field: 'path', title: '节点路径', align: 'center'},
                {
                    field: 'available', title: '状态', align: 'center', templet: function (d) {
                        return d.available == 1 ? '<font color=blue>可用</font>' : '<font color=red>禁用</font>';
                    }
                },
                {field: "creator", title: "创建人", align: "center"},
                {field: 'createTime', title: '创建时间', align: 'center'},
                {fixed: 'right', title: '操作', toolbar: '#categoryRowBar', align: 'center', width: 200}
            ]]
        });

        // 初始化树形组件
        var parentTree = dtree.renderSelect({
            elem: "#parentTree",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            method: "GET",
            response: {message: "msg", statusCode: 0},
            url: "/category/tree",

        });
        // 节点点击事件：设置parentId
        dtree.on("node(parentTree)", function (obj) {
            $("#parentId").val(obj.param.nodeId);
            form.render(); // 刷新表单状态
        });

        // 工具栏事件
        table.on("toolbar(categoryTable)", function (obj) {
            if (obj.event === 'add') {
                openAddLayer();
            }
        });

        // 行工具事件
        table.on("tool(categoryTable)", function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'edit':
                    openEditLayer(data);
                    break;
                case 'delete':
                    deleteCategory(data);
                    break;
            }
        });

        var mainIndex, url;

        // 提供给左侧树的刷新方法
        window.reloadTable = function (parentId) {
            tableIns.reload({
                where: {parentId: parentId}, // 参数名与后端接口一致
                page: {curr: 1}
            });
        };

        // 打开添加窗口
        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['500px', '400px'],
                title: '添加分类',
                shade: 0.6,
                zIndex: layer.zIndex,
                success: function () {
                    $("#dataFrm")[0].reset();
                    $("#parentId").val("");
                    parentTree.selectVal("");
                    form.val("dataFrm", {
                        available: "1"  // 确保可用状态默认选中
                    });
                    form.render('radio'); // 刷新单选按钮渲染
                    url = "/category/save";
                }
            });
        }

        // 打开编辑窗口

        function openEditLayer(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['500px', '400px'],
                title: '编辑分类',
                shade: 0.6,
                zIndex: layer.zIndex,
                success: function () {
                    form.val("dataFrm", {
                        id: data.id,
                        name: data.name,
                        parentId: data.parentId,
                        path: data.path,
                        available: data.available.toString(),
                        type: data.type // 确保 data.type 是 "0" 或 "1"
                    });
                    dtree.dataInit("parentTree", data.parentId);
                    dtree.selectVal("parentTree");
                    form.render('radio');
                    url = "/category/save";
                }
            });
        }


        // 表单提交响应处理调整
        form.on('submit(doSubmit)', function (data) {
            data.field.parentId = $("#parentId").val();

            // 显示加载中状态
            var loadIndex = layer.load(2);

            $.ajax({
                url: url,
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(data.field),
                success: function (res) {
                    layer.close(loadIndex); // 关闭加载中

                    if (res.code === 200) {
                        layer.msg(res.msg, {icon: 1, time: 1000}, function() {
                            // 确保所有操作完成后关闭窗口
                            tableIns.reload();
                            window.parent.left.parentTree.reload(); // 调用左侧树的刷新方法
                            layer.close(mainIndex); // 关闭当前弹窗

                            // 额外检查：如果窗口仍未关闭，强制关闭
                            if (layer.getFrameIndex(window.name) !== -1) {
                                layer.close(layer.getFrameIndex(window.name));
                            }
                        });
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                error: function (xhr) {
                    layer.close(loadIndex);
                    layer.msg("请求失败: " + xhr.statusText, {icon: 2});
                }
            });
            return false;
        });

        // 删除分类
        function deleteCategory(data) {
            // 先检查是否有子节点
            $.post("/category/checkCatHasChildrenNode", {id: data.id}, function(result) {
                if (result.value) { // 存在子节点，禁止删除
                    layer.msg("当前分类存在子节点，无法删除！");
                } else { // 无子节点，弹出确认框
                    layer.confirm('确定删除【' + data.name + '】分类吗？', {icon: 3, title: '提示'}, function (index) {
                        $.ajax({
                            url: "/category/delete/" + data.id,
                            type: "DELETE",
                            success: function (res) {
                                if (res.code === 200) { // 后端需确保成功返回 code=200
                                    tableIns.reload(); // 刷新右侧表格
                                    window.parent.left.parentTree.reload(); // 刷新左侧树
                                }
                                layer.msg(res.msg);
                            },
                            error: function (xhr) {
                                layer.msg("请求失败: " + xhr.statusText);
                            }
                        });
                        layer.close(index);
                    });
                }
            });
        }

    });
</script>
</body>
</html>